package com.paishen.peiniwan.frame.widget;

/**
 * Created by peng on 2015/12/7.
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.R;

import java.util.ArrayList;
import java.util.List;

public class StarView extends LinearLayout {

    public static final int TOTAL_COUNT = 5;
    private float light = TOTAL_COUNT;

    public StarView(Context context) {
        this(context, null);
    }


    private int bmpStartLight, bmpStarNormal;

    private boolean editable = false;

    private List<ImageView> imgs = new ArrayList<>();

    public StarView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setOrientation(HORIZONTAL);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StarView);
        boolean large = a.getBoolean(R.styleable.StarView_large, false);
        a.recycle();

        bmpStartLight = large ? R.mipmap.common_star_40_light : R.mipmap.common_star_30_light;
        bmpStarNormal = large ? R.mipmap.common_star_40_normal : R.mipmap.common_star_30_normal;

        final OnClickListener l = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editable) {
                    int curr = (int) v.getTag();
                    setLightStarCount(curr * 1f / TOTAL_COUNT);
                }
            }
        };

        LayoutParams lpImgs = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lpImgs.setMargins(0, 0, BaseUtil.dip2px(5), 0);
        for (int i = 1; i <= TOTAL_COUNT; i++) {
            ImageView img = new ImageView(context);
            img.setImageResource(bmpStarNormal);
            img.setTag(i);
            img.setLayoutParams(lpImgs);
            img.setOnClickListener(l);
            imgs.add(img);
            addView(img);
        }

        light = 0;
        refresh();
    }


    /**
     * @param percent range[0.0 - 1.0]
     */
    public void setLightStarCount(float percent) {


        light = percent * TOTAL_COUNT;
        light = (int) (light + 0.5);

        if (light < 1) light = 1;
        else if (light > TOTAL_COUNT) light = TOTAL_COUNT;

        refresh();
    }

    private void refresh() {
        for (int i = 0; i < imgs.size(); i++) {
            ImageView iv = imgs.get(i);
            iv.setImageResource(i > light - 1 ? bmpStarNormal : bmpStartLight);
        }
    }

    public void setEditable(boolean editable) {
        this.editable = editable;
    }


    public int getLightCount() {
        return (int) (light + 0.5f);
    }
}